package com.zzyl.nursing.service.impl;

import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zzyl.nursing.service.IWeChatService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
public class WeChatServiceImpl implements IWeChatService {

    @Value("${weChat.appId}")
    private String appId;
    @Value("${weChat.secret}")
    private String secret;

    private static String openUrl = "https://api.weixin.qq.com/sns/jscode2session";
    private static String phoneUrl = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";
    private static String tokenUrl = "https://api.weixin.qq.com/cgi-bin/token";

    @Override
    public String getOpenid(String code) {

        Map<String, Object> map = Map.of("appid", appId,
                "secret", secret,
                "js_code", code,
                "grant_type", "authorization_code");
        HttpResponse httpResponse = HttpUtil.createRequest(Method.GET, openUrl)
                .form(map).execute();
        if (httpResponse.isOk()) {
            String body = httpResponse.body();
            JSONObject entries = JSONUtil.parseObj(body);
            String openid = entries.getStr("openid");
            return openid;
        }
        return null;
    }

    @Override
    public String getPhoneNumber(String phoneCode) {
        Map<String, Object> map = Map.of("code",phoneCode);

        HttpResponse httpResponse = HttpUtil.createRequest(Method.POST, phoneUrl + getAccessToken())
                .body(JSONUtil.toJsonStr(map)).execute();
        if (httpResponse.isOk()) {
            String body = httpResponse.body();
            JSONObject entries = JSONUtil.parseObj(body);
            String phoneNumber = entries.getByPath("phone_info.phoneNumber", String.class);

            return phoneNumber;
        }
        return null;
    }

    public String getAccessToken() {
        Map<String, Object> map = Map.of("appid", appId,
                "secret", secret,
                "grant_type", "client_credential");
        HttpResponse httpResponse = HttpUtil.createRequest(Method.GET, tokenUrl)
                .form(map).execute();
        if (httpResponse.isOk()) {
            String body = httpResponse.body();
            JSONObject entries = JSONUtil.parseObj(body);
            String accessToken = entries.getStr("access_token");
            return accessToken;
        }
        return null;
    }
}
